<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChCorpTag;
use Mine\Abstracts\AbstractMapper;

class ChCorpTagMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChCorpTag::class;
    }

    public function findById(string $id)
    {
        return $this->model::query()->where('id',$id)->first();
    }

    public function getListByCorpId(mixed $corpId): array
    {
        return ChCorpTag::query()
            ->select(['id', 'name', 'group_id','contact_cnt'])
            ->where('corp_id', $corpId)
            ->where('label_type',1)
            ->where('is_deleted',0)
            ->orderBy('create_time', 'desc')
            ->get()->toArray();
    }

    public function getListByRobotId(mixed $robotId): array
    {
        return ChCorpTag::query()
            ->select(['id', 'name', 'group_id','contact_cnt'])
            ->where('robot_id', $robotId)
            ->where('label_type',2)
            ->where('is_deleted',0)
            ->orderBy('create_time', 'desc')
            ->get()->toArray();
    }

    /**
     * 检查个人标签名称是否已存在
     * @param string $name
     * @param string $id
     * @return bool
     */
    public function checkPersonalTagNameExist(mixed $robotId,string $name,string $id = ''): bool
    {
        return $this->model::query()
            ->where('robot_id',$robotId)
            ->where('name',$name)
            ->where('label_type',2)
            ->when(!empty($id),function ($query) use ($id){
                $query->where('id','<>',$id);
            })->exists();
    }

    public function updateContactCnt(array $tagIds,int $contactCnt): void
    {
        $query = $this->model::query()
            ->whereIn('id',$tagIds);

        if($contactCnt > 0){
            $query->increment('contact_cnt',$contactCnt);
        }else{
            $query->decrement('contact_cnt',$contactCnt);
        }
    }
}